package com.xzjt.web.controller;

import cn.hutool.json.JSONObject;

import com.xzjt.common.components.JwtToken;
import com.xzjt.common.components.RedisService;
import com.xzjt.common.utils.*;
import com.xzjt.web.annotation.SysLogAnnotation;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.service.LoginService;
import com.xzjt.web.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: LoginController
 * @Author: yuandong
 * @Date 2021/10/9 15:47
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;



    /**
     * 用户登录
     * @param sysUser
     * @return
     */
    @SysLogAnnotation("用户登录")
    @PostMapping("/login")
    public R<?> login(@RequestBody SysUser sysUser){


        //验证码校验
        if (StringUtils.isBlank(sysUser.getCaptchacode()) || StringUtils.isBlank(sysUser.getKey())) {
            return R.error("999","验证码错误");
        }

        if (!sysUser.getCaptchacode().equals(redisService.hget(Const.CAPTCHA_KEY, sysUser.getKey()))) {
            return R.error("999","验证码错误");
        }

        // 一次性使用，清空缓存中的验证码
        redisService.hdel(Const.CAPTCHA_KEY, sysUser.getKey());


        //根据用户名和密码在本地查询用户
        SysUser user = this.sysUserService.selectLoginUser(sysUser);
        if(user==null){
            return R.error("999","用户不存在");
        }

        String salt=user.getSalt();                              //盐值暂定使用每个用户的用户名
        String password= MD5Utils.md5(sysUser.getPassword()) ;   //用户前台输入的明文密码

        String passwordDb = user.getPassword();                 //该用户数据库中已经保存的加密后的密码

        if(!PasswordUtils.verify(password, salt, passwordDb)){  // DBpassword--> c2b632dc87637a5fd03fdf9b61693d17
            return R.error("999","密码错误");
        }

        //用户生成token(将token-用户信息（用户实体） 存放到redis中)
        String token =loginService.createToken(user);
        if(StringUtils.isBlank(token)){
            return R.error("999","token生成失败");
        }

        JwtToken jwtToken=new JwtToken(token);
        Subject subject = SecurityUtils.getSubject();
        subject.login(jwtToken);


        JSONObject ret = new JSONObject();
        ret.put("user", user);
        ret.put("token", token);

        return R.ok(ret);
    }


    /**
     * 退出登录
     * @param token
     * @return
     */
    @PostMapping("/logout")
    public R logout(@RequestHeader String token){
        //**退出登录
        SecurityUtils.getSubject().logout();
        // 从缓存中移除Token
        redisService.del(token);
        return R.ok();
    }


}
